using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using LS.Digitize;

namespace LS.GameKit.Editor
{
    [CustomPropertyDrawer(typeof(AssetInfo), true)]
    public class AssetInfoInspector : PropertyDrawer
    {
        private string m_Guid = null;
        private string m_FullPath = null;
        private string m_AssetName = null;
        private string m_Directory = null;
        private string m_Extension = null;
        
        private Object m_Asset = null;
        private AssetInfo m_Instance = null;
        
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            AssetInfo info = (AssetInfo)property.boxedValue;
            Setup(info);
            
            float height = EditorGUIUtility.singleLineHeight;
            Rect rect = new Rect(position.x, position.y, position.width, height);
            Object asset = EditorGUI.ObjectField(rect, m_Asset, typeof(Object), false);
            if (asset != m_Asset)
            {
                Setup(asset, property);
            }
        }

        private void Setup(AssetInfo info)
        {
            m_Instance = info;
            m_FullPath = info?.FullPath ?? string.Empty;
            m_AssetName = info?.FileName ?? string.Empty;
            m_Extension = info?.FileExtension ?? string.Empty;
            m_Directory = info?.FileDirectory ?? string.Empty;
            m_Guid = info?.Guid ?? string.Empty;

            if (!string.IsNullOrEmpty(m_FullPath))
            {
                m_Asset = AssetDatabase.LoadAssetAtPath<Object>(m_FullPath);
            }
        }
        
        private void Setup(Object asset, SerializedProperty property)
        {
            m_Asset = asset;
            if (asset == null)
            {
                m_Guid = string.Empty;
                m_FullPath = string.Empty;
                m_AssetName = string.Empty;
                m_Extension = string.Empty;
                m_Directory = string.Empty;
                property.boxedValue = m_Instance = AssetInfo.Empty;
                return;
            }
            
            m_FullPath = AssetDatabase.GetAssetPath(asset);
            m_AssetName = Path.GetFileNameWithoutExtension(m_FullPath);
            m_Directory = Path.GetDirectoryName(m_FullPath);
            m_Extension = Path.GetExtension(m_FullPath);
            m_Guid = AssetDatabase.AssetPathToGUID(m_FullPath);
            Apply(property);
        }

        private void Apply(SerializedProperty property)
        {
            m_Instance = new AssetInfo(m_AssetName, m_Directory, m_Extension, m_Guid);
            property.boxedValue = m_Instance;
            property.serializedObject.ApplyModifiedProperties();
        }
    }
}
